﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using BIS.Portal.Core.Base;
using BIS.Portal.Core.BO;
using BIS.Portal.Core.Entity;
using BIS.Portal.Core.Global;
using BIS.Portal.Modules.CMS.BO;
using BIS.SecurityManagement;

using BIS.Portal.Modules.CMS.Entity;
using BIS.Utility.Converter;

namespace BIS.Portal.Modules.CMS.Adm
{
    public partial class AdminCmsArticleControl : ControlBase
    {
        private const string SessionArticleIdName = "_article_id";
        private int CategoryId
        {
            get
            {
                return Functions.GetInt(Request.QueryString[QueryStringKeys.CategoryId]);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            BinDataDropDownListCategory();
            BindDataIntoGridView();
            btnDelete.Attributes.Add("onclick", "return confirm('Are u sure u want to delete?');");
            hblAddNewArticle.NavigateUrl = WebHelpers.GetLink(UrlRewriteRules.UpdateArticle, CmsArticlePageAlias,
                                                             new string[] { QueryStringKeys.ArticleId, QueryStringKeys.ArticleUpdateAction },
                                                             new string[] { "0", "0" });
        }

        #region Session properties
        public string SearchByKeyword
        {
            get { return (null != Session["SearchByKeyword"] ? Session["SearchByKeyword"].ToString() : ""); }
            set { Session["SearchByKeyword"] = value; }
        }
        public int SearchByCategoryId
        {
            get { return (null != Session["SearchByCategoryId"] ? int.Parse(Session["SearchByCategoryId"].ToString()) : -1); }
            set { Session["SearchByCategoryId"] = value; }
        }
        public int SearchByIsHot
        {
            get { return (null != Session["SearchByIsHot"] ? int.Parse(Session["SearchByIsHot"].ToString()) : -1); }
            set { Session["SearchByIsHot"] = value; }
        }
        public int SearchByStatus
        {
            get { return (null != Session["SearchByStatus"] ? int.Parse(Session["SearchByStatus"].ToString()) : -1); }
            set { Session["SearchByStatus"] = value; }
        }
        public DateTime SearchByDateStart
        {
            get { return (null != Session["SearchByDateStart"] ? DateTime.Parse(Session["SearchByDateStart"].ToString()) : DateTime.Parse("1900-01-01")); }
            set { Session["SearchByDateStart"] = value; }
        }
        public DateTime SearchByDateEnd
        {
            get { return (null != Session["SearchByDateEnd"] ? DateTime.Parse(Session["SearchByDateEnd"].ToString()) : DateTime.Parse("9999-12-31")); }
            set { Session["SearchByDateEnd"] = value; }
        }
        #endregion

        #region Search

        private void SaveFormDataIntoSession()
        {
            // 
            SearchByKeyword = txtSearch.Text;
            SearchByIsHot = int.Parse(ddlIsHotArticle.SelectedItem.Value);
            SearchByStatus = int.Parse(ddlStatus.SelectedItem.Value);
            SearchByCategoryId = int.Parse(ddlCategoryName.SelectedItem.Value);
            if (!string.IsNullOrEmpty(txtSearchFromDate.Text))
            {
                SearchByDateStart = DateTime.Parse(txtSearchFromDate.Text);
                if (!string.IsNullOrEmpty(txtSearchToDate.Text))
                {
                    SearchByDateEnd = DateTime.Parse(txtSearchToDate.Text);
                }
                else
                {
                    SearchByDateEnd = DateTime.Parse("9999-12-31");
                }
            }
            else
            {
                SearchByDateStart = DateTime.Parse("1900-01-01");
                if (!string.IsNullOrEmpty(txtSearchToDate.Text))
                {
                    SearchByDateEnd = DateTime.Parse(txtSearchToDate.Text);
                }
                else
                {
                    SearchByDateEnd = DateTime.Parse("9999-12-31");
                }
            }



        }

        private void BindDataIntoGridView()
        {
            //
            int languageUseId = 0;
            try
            {
                languageUseId = PortalContext.LanguageInUseId;
            }
            catch (Exception ex)
            {

                Console.Write(ex.Message);
                languageUseId = 1;
            }
            IList<AdminCmsArticleEntity> list = AdminCmsArticleBO.SearchArticle(SearchByKeyword, SearchByCategoryId, SearchByIsHot, SearchByStatus, languageUseId, SearchByDateStart, SearchByDateEnd);
            grvArticle.DataSource = list;
            grvArticle.DataKeyNames = new string[] { "article_id" };
            grvArticle.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            SaveFormDataIntoSession();
            BindDataIntoGridView();
        }

        #endregion

        #region Bind DropDrownList
        protected void BinDataDropDownListCategory()
        {
            int languageUseId = 0;
            try
            {
                languageUseId = PortalContext.LanguageInUseId;
            }
            catch (Exception ex)
            {

                Console.Write(ex.Message);
                languageUseId = 1;
            }            

            IList<AdminCmsCategoryEntity> list = AdminCmsCategoryBO.GetByLanguageInUseId(languageUseId);
            IList<AdminCmsCategoryEntity> listAdminCategoryEntity = new List<AdminCmsCategoryEntity>();
            AdminListViewUtility.ParseList(0, ref list, ref listAdminCategoryEntity);

            // binding dropdownlist            
            listAdminCategoryEntity.Insert(0, new AdminCmsCategoryEntity()
            {
                Category_id = 0,
                Category_name = "---Toàn bộ---"
            });

            AdminListViewUtility.AddDotList(ref listAdminCategoryEntity);
            ddlCategoryName.Items.Clear();
            for (int i = 0; i < listAdminCategoryEntity.Count; i++)
            {
                ListItem item = new ListItem();
                item.Text = listAdminCategoryEntity[i].Category_name;
                item.Value = listAdminCategoryEntity[i].Category_id.ToString();
                if (listAdminCategoryEntity[i].Category_type == 3)
                {
                    item.Attributes.Add("disabled", "disabled");
                }
                ddlCategoryName.Items.Add(item);
            }          
            //ddlCategoryName.DataSource = listAdminCategoryEntity;
            //ddlCategoryName.DataValueField = "category_id";
            //ddlCategoryName.DataTextField = "category_name";            
            //ddlCategoryName.DataBind();              
            if (CategoryId != null)
            {
                ddlCategoryName.SelectedValue = CategoryId.ToString();
            }
        }

        #endregion

        #region Page Change
        protected void grvArticle_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvArticle.PageIndex = e.NewPageIndex;
            BindDataIntoGridView();
        }
        #endregion

        #region Delete Data
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //Check toan bo checkbox
            for (int i = 0; i < grvArticle.Rows.Count; i++)
            {
                CheckBox cb = grvArticle.Rows[i].FindControl("chkSell") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    if (grvArticle.DataKeys[i] != null)
                    {
                        int test = Int32.Parse(grvArticle.DataKeys[i].Value.ToString());
                        AdminCmsArticleBO.DeleteArticle(test);
                    }
                }
            }            
            BindDataIntoGridView();
        }
        #endregion


        #region Update Status In Page
        protected void btnUpdateNews_Click(object sender, EventArgs e)
        {
            int article = 0;
            int temp1 = 0;
            int temp2 = 0;
            CheckBox chk;
            DropDownList ddl;
            if (grvArticle != null)
            {
                for (int i = 0; i < grvArticle.Rows.Count; i++)
                {
                    int.TryParse(grvArticle.DataKeys[i].Value.ToString(), out article);
                    chk = grvArticle.Rows[i].FindControl("chkIsHotArticle") as CheckBox;
                    ddl = grvArticle.Rows[i].FindControl("ddlGridStatus") as DropDownList;
                    if (chk != null)
                        if (chk.Checked)
                            temp1 = 1;
                    if (ddl != null)
                        temp2 = int.Parse(ddl.SelectedItem.Value);
                    if (!AdminCmsArticleBO.UpdateStatusInPage(article, temp1, temp2))
                    {                        
                        return;
                    }
                }
                BindDataIntoGridView();
            }

        }
        #endregion

        #region Propeties setting

        public string CmsArticlePageAlias
        {
            get
            {
                try
                {
                    return GetControlSetting<string>(
                                                     ModuleSettingNames.AdminCmsArticleControl.AdminCmsArticle_ContentPage,
                                                     PortalContext.LanguageAlias);
                }
                catch (Exception)
                {
                    return "";
                }
            }
        }

        protected void grvArticle_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                AdminCmsArticleEntity entity = e.Row.DataItem as AdminCmsArticleEntity;

                HyperLink llkEdit = e.Row.FindControl("llkEdit") as HyperLink;
                HyperLink llkCopy = e.Row.FindControl("llkCopy") as HyperLink;
                CheckBox chkIsHotArticle = e.Row.FindControl("chkIsHotArticle") as CheckBox;
                DropDownList ddlStatus = e.Row.FindControl("ddlGridStatus") as DropDownList;
                if (chkIsHotArticle != null)
                {
                    if (entity.Is_hot_article == 1)
                        chkIsHotArticle.Checked = true;
                    else
                        chkIsHotArticle.Checked = false;
                }
                if (ddlStatus != null)
                {
                    if (entity.Status == 0)
                        ddlStatus.SelectedValue = "0";
                    if (entity.Status == 1)
                        ddlStatus.SelectedValue = "1";
                    if (entity.Status == 99)
                        ddlStatus.SelectedValue = "99";
                }
                if (null != llkEdit)
                {
                    llkEdit.NavigateUrl = WebHelpers.GetLink(UrlRewriteRules.UpdateArticle, CmsArticlePageAlias,
                                                             new string[] { QueryStringKeys.ArticleId, QueryStringKeys.ArticleUpdateAction },
                                                             new string[] { entity.Article_id.ToString(), "1" });
                }
                if (null != llkCopy)
                {
                    llkCopy.NavigateUrl = WebHelpers.GetLink(UrlRewriteRules.UpdateArticle, CmsArticlePageAlias,
                                                             new string[] { QueryStringKeys.ArticleId, QueryStringKeys.ArticleUpdateAction },
                                                             new string[] { entity.Article_id.ToString(), "0" });
                }
            }
        }

        #endregion

    }
}